package com.request.service.impl.shop.sy;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.request.common.constants.RedisConstant;
import com.request.common.enums.RechargeTypeEnum;
import com.request.common.enums.SignTypeEnum;
import com.request.common.enums.SyOrderStatusEnum;
import com.request.common.utils.HttpUtils;
import com.request.common.utils.SignUtils;
import com.request.entity.PhoneOrderWaitCheck;
import com.request.service.QueryOrderProcessor;
import com.request.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * Description:
 * Create DateTime: 2020/6/10 16:44
 *
 * 

 */
@Slf4j
@Service
public class SyQueryOrderProcessor implements QueryOrderProcessor {
    private static Map<String, String> HEADER_MAP = new HashMap<>(2);

    static {
        HEADER_MAP.put("Content-Type","application/json;charset=utf-8");
    }


    @Resource
    private RedisService redisService;

    @Resource
    private ThreadPoolExecutor handlerOrderExecutor;

    @Override
    public void sendRequest(PhoneOrderWaitCheck orderWaitCheck) {
        handlerOrderExecutor.execute(() -> executeWaitOrderQuery(orderWaitCheck));
    }

    /**
     * 执行待查询订单查询
     *
     * @param phoneOrderWaitCheck
     */
    private void executeWaitOrderQuery(PhoneOrderWaitCheck phoneOrderWaitCheck) {
        Map<String, Object> params = new HashMap<>(2);
        String result = null;
        try {
            String querySite = phoneOrderWaitCheck.getQuerySite();
            String platformOrderNo = phoneOrderWaitCheck.getPlatformOrderNo();

            params.put("coopid",phoneOrderWaitCheck.getAppId());
            params.put("tranid", platformOrderNo);

            //生成签名
            TreeMap<String, String> signMap = new TreeMap<>();
            signMap.put("coopid", phoneOrderWaitCheck.getAppId());
            signMap.put("tranid", platformOrderNo);

            String sign = SignUtils.syGenerateSignature(signMap, SignTypeEnum.MD5, phoneOrderWaitCheck.getAppKey());
            params.put("sign", sign);

            log.info("【Sy】【查单】拼接的参数为:{}",params.toString());
            String param = JSON.toJSONString(params);
            //result = JsonHttpClientUtils.httpsPost(querySite, param, "UTF-8");
            result = sendRequestForPushOrder(querySite, param);
            log.info("【Sy】【查单】结果:{}",result);

            JSONObject jsonObject = JSONObject.parseObject(result);
            String orderStatus = jsonObject.getString("failedCode");
            if (SyOrderStatusEnum.getByCode(orderStatus) == null) {
                throw new RuntimeException("订单相应失败,返回结果code为:"+orderStatus);
            }
            String message = jsonObject.getString("failedReason");
            String orderSn = jsonObject.getString("orderNo");
            String shopOrderNo = jsonObject.getString("tranId");

            phoneOrderWaitCheck.setOrderSn(orderSn);
            phoneOrderWaitCheck.setMessage(message);
            phoneOrderWaitCheck.setShopOrderNo(shopOrderNo);

            SyOrderStatusEnum syOrderStatusEnum = SyOrderStatusEnum.getByCode(orderStatus);
            switch (syOrderStatusEnum) {
                case SUCCESS :
                    phoneOrderWaitCheck.setStatus(1);
                    saveWaitOrderQueryForSuccess(phoneOrderWaitCheck);
                    break;
                case FAILED:
                    phoneOrderWaitCheck.setStatus(0);
                    saveWaitOrderQueryForSuccess(phoneOrderWaitCheck);
                    break;
                case PROCESSING:
                    saveWaitOrderQueryForProcessing(phoneOrderWaitCheck);
                    break;
                default:
                    saveWaitOrderQueryForProcessing(phoneOrderWaitCheck);
                    break;
            }
        } catch (Exception e) {
            saveWaitOrderQueryForProcessing(phoneOrderWaitCheck);
            log.error("【Sy】【超时检查】请求商户出现异常，待检查订单信息为：{}, 参数为：{}, 响应结果为:{}, 详情为：{}",
                    phoneOrderWaitCheck, params.toString(), result, e);
        }

    }
    /**
     * 放入失败队列 (废弃)
     */
    @Deprecated
    private void saveWaitOrderQueryForFailed(PhoneOrderWaitCheck phoneOrderWaitCheck) {
        redisService.lPush(RedisConstant.PUSH_ORDER_WAIT_CHECK_FAILED, JSON.toJSONString(phoneOrderWaitCheck));
    }
    /**
     * 放入成功队列
     */
    private void saveWaitOrderQueryForSuccess(PhoneOrderWaitCheck phoneOrderWaitCheck) {
        redisService.lPush(RedisConstant.PUSH_ORDER_WAIT_CHECK_SUCCESS, JSON.toJSONString(phoneOrderWaitCheck));
    }

    /**
     * 放入处理中队列
     */
    private void saveWaitOrderQueryForProcessing(PhoneOrderWaitCheck phoneOrderWaitCheck) {
        if (!RechargeTypeEnum.SLOW.getCode().equals(phoneOrderWaitCheck.getRechargeType())) {
            redisService.lPush(RedisConstant.PUSH_ORDER_WAIT_CHECK_PROCESSING, JSON.toJSONString(phoneOrderWaitCheck));
        }
    }

    /**
     * 发送Http请求
     *
     * @param url    请求路径
     * @param pushOrderForHf  参数
     * @return 响应结果
     */
    private String sendRequestForPushOrder(String url, String pushOrderForHf) {
        return HttpUtils.jsonPost(url,pushOrderForHf);
    }
}
